package com.zs.grain.ui

import android.app.Application
import android.graphics.drawable.Drawable
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import com.jeremyliao.liveeventbus.LiveEventBus
import com.zs.grain.R
import com.zs.grain.service.DataService
import com.zs.grain.service.DeviceService
import com.xnkj1688.semplibrary.mvvm.*
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
import java.util.*
import kotlin.concurrent.schedule

class MenusViewModel @Inject constructor(
    val mApp: Application,
    val mDataService: DataService,
    val mDeviceService: DeviceService
) : BaseViewModel(mApp) {
    val isMachineInit = MutableLiveData<Boolean>()
    val preMore = MutableLiveData<Boolean>()
    val nextMore = MutableLiveData<Boolean>()
    val isProductForgotTake = MutableLiveData<Boolean>()
    val isProductForgotTakeBut = MutableLiveData<Boolean>()
    val isReady = MutableLiveData<Boolean>()
    var maintenance = MutableLiveData<String>()
    var machineInit = MutableLiveData<String>()
    var proUntake = MutableLiveData<String>()
    val menuViewModels = MutableLiveData<MutableList<MenuViewModel>>()
    //val tmpMenuViewModels = MutableLiveData<MutableList<MenuViewModel>>()
    val m1 = MutableLiveData<Drawable>()
    val m2 = MutableLiveData<Drawable>()
    val downCount = MutableLiveData<Int>()
    var allProductCanSell = false
    var butHasClick = false
    var currentScreen = 0
    var goodNum = 0
    val perNum = 6
    val perHeight = 1120
    private var mStatusTimer: Timer? = null
    val phoneNum = mDataService.phoneNum
    init {
        isReady.value = true
        isMachineInit.value = false
        preMore.value = false
        nextMore.value = false
        isProductForgotTake.value = false
        isProductForgotTakeBut.value = false
        maintenance.value = "res://${mApp.packageName}/${R.mipmap.maintenance}"
        machineInit.value = "res://${mApp.packageName}/${R.mipmap.ismachineinit}"
        proUntake.value  = "res://${mApp.packageName}/${R.mipmap.prountake}"
        //this.startAdsPlayTimer()
    }

    fun init(group: Int) {
        when (group) {
            1 -> {
                m1.value = mApp.getDrawable(R.mipmap.m11)
                m2.value = mApp.getDrawable(R.mipmap.m22)
            }
            2 -> {
                m1.value = mApp.getDrawable(R.mipmap.m12)
                m2.value = mApp.getDrawable(R.mipmap.m21)
            }
        }
        uacs = mDeviceService.unvaliableComponents
        menuViewModels.value = this.getMenuViewModels(group)
//this.uiNotify.postValue(this.getNotify("showGuideView"))
        startStatusTimer()
    }
    private lateinit var uacs:Array<Int>
    fun refreshComponentStatus() {
        val uac: Array<Int> = mDeviceService.unvaliableComponents
        if(uac contentEquals uacs) {
            //println("kkkkkkkkkkkkkk")
        }else{
            uacs = uac
            this.init(1)
         }
    }

    fun refreshButView(currentScreen:Int){
        when(currentScreen){
            0 -> {
                preMore.postValue(false)
                nextMore.postValue(true)
            }
            goodNum/perNum ->{
                preMore.postValue(true)
                nextMore.postValue(false)
            }
            else -> {
                preMore.postValue(true)
                nextMore.postValue(true)
            }

        }
    }

    fun onPrePage(){
        nextMore.postValue(true)
        //if(currentScreen>=1) refreshButView(--currentScreen)
        var bundle = Bundle()
        bundle.putInt("x", -60)
        bundle.putInt("y", -perHeight)
        LiveEventBus.get("RefreshRV", Bundle::class.java).post(bundle)
    }

    fun onNextPage(){
        preMore.postValue(true)
        //if(currentScreen< goodNum/perNum ) refreshButView(++currentScreen)
        var bundle = Bundle()
        bundle.putInt("x", 60)
        bundle.putInt("y", perHeight)
        LiveEventBus.get("RefreshRV", Bundle::class.java).post(bundle)
    }

    fun onClickDeploy() {
        m1.value = mApp.getDrawable(R.mipmap.m11)
        m2.value = mApp.getDrawable(R.mipmap.m22)
        menuViewModels.value = this.getMenuViewModels(1)
    }

    fun onClickPacket() {
        m1.value = mApp.getDrawable(R.mipmap.m12)
        m2.value = mApp.getDrawable(R.mipmap.m21)
        menuViewModels.value = this.getMenuViewModels(2)
    }

    fun onClickMenu(vm: MenuViewModel) {
        if (!(vm.enable.value ?: true)) return

        var bundle = Bundle()
        bundle.putString("UI", "Deploy")
        bundle.putLong("MenuNo", vm.mMenu.no)
        LiveEventBus.get("SwitchUI").post(bundle)
    }

    fun onTakeProduct(){
        if(!butHasClick) {
            butHasClick = true
            isProductForgotTakeBut.postValue(false)
            this.uiNotify.postValue(this.getNotify("HideButton"))
            Single.just("")
                .subscribeOn(Schedulers.io())
                .subscribe({
                    mDeviceService.takeProduct()
                }, {
                    it.printStackTrace()
                })
        }
    }

    private fun getMenuViewModels(group: Int): MutableList<MenuViewModel> {
        val list = ArrayList<MenuViewModel>()
        val list2 = ArrayList<MenuViewModel>()
        for (item in mDataService.getMenus(group)) {


            val model = MenuViewModel(mApp, item)
            var good = mDataService.getGood(item.goodId)
            if (good != null) {
                if (item.logoId == null) item.logoId = good?.logoId
                if (item.name == null) item.name = good?.name

                model.enable.value = this.checkEnable(good.id)
                model.beforeEnable.value = model.enable.value
            } else {
                model.enable.value = false
            }
            if (item.logoId != null) {
                val image = mDataService.getImage(item.logoId)
                model.uri.value = "file://${mDataService.imagesPath}/${image?.fileName}"
//                model.uri.
//                value = "res://${mApp.packageName}/${R.mipmap.p1}"
            }
            if (model.enable.value == true) {
                list.add(model)
            } else {
                list2.add(model)
            }
        }
        list.addAll(list2)
        goodNum = list.size
        if(list.size>perNum) nextMore.postValue(true)
        return list
    }

    private fun checkEnable(goodId: Long) = mDeviceService.checkProductAvaliable(goodId)


    fun startStatusTimer() {
        this.mStatusTimer?.cancel()
        this.mStatusTimer = Timer()
        this.mStatusTimer?.schedule(1000, 1000, {
            var status = mDeviceService.isReady
            isReady.postValue(status)

            var status2 = mDeviceService.isMachineInit
                isMachineInit.postValue(status2)

            var status3 = mDeviceService.isProForgotTake
                isProductForgotTake.postValue(status3)
            if(status3&&!butHasClick){
                isProductForgotTakeBut.postValue(true)
            }
        })
    }

    fun stopStatusTimer() {
        this.mStatusTimer?.cancel()
        this.mStatusTimer = null
    }

    private var times = 0
    private var mAdsTimer: Timer? = null
    fun startAdsPlayTimer(){
        times = 0
        this.downCount.postValue(120)
        this.mAdsTimer = Timer()
        this.mAdsTimer?.schedule(1000,1000,{
            var count = Math.max(0, (downCount.value ?: 1) - 1)
            downCount.postValue(count)
            if (count <= 0) stopAdsTimer()
            if (count % 30 != 1) return@schedule
            times++
        })
    }

    fun stopAdsTimer() {
        this.mAdsTimer?.cancel()
        this.mAdsTimer = null
        playMainAds()//
    }

    fun playMainAds(){

        //方式二:使用新增的Fragment住当前页面产品区域
        //传入首页的播放进度?
//        var bundle = Bundle()
//        bundle.putString("UI", "Ads")
        //LiveEventBus.get().with("SwitchUI").post(bundle)

        LiveEventBus.get("RefreshVideoView").post(true)//是否隐藏
    }
}
